from django import template
from django.contrib.auth.models import User, Group, Permission

register = template.Library()

def permission_boxes():
    boxes = ""
    for permission in Permission.objects.all().order_by('id'): 
        boxes = boxes + "<tr><td>"+permission.name+"</td><td><input type='checkbox' value='"+str(permission.id)+"' name='inputPermissions[]'"   
        boxes = boxes +"></td></tr>"
        
    return boxes

def user_permission_boxes(user):
    boxes = ""
    user_permissions = user.user_permissions.values('id')
    for permission in Permission.objects.all().order_by('id'): 
        boxes = boxes + "<tr><td>"+permission.name+"</td><td><input"
        if {'id':permission.id} in user_permissions:
            boxes = boxes + " checked=\"checked\" "
        boxes = boxes + " type='checkbox' value='"+str(permission.id)+"' name='inputPermissions[]'></td></tr>"
        
    return boxes

def group_permission_boxes(group):
    boxes = ""
    group_permissions = group.permissions.values('id')
    for permission in Permission.objects.all().order_by('id'): 
        boxes = boxes + "<tr><td>"+permission.name+"</td><td><input"
        if {'id':permission.id} in group_permissions:
            boxes = boxes + " checked=\"checked\" "
        boxes = boxes + " type='checkbox' value='"+str(permission.id)+"' name='inputPermissions[]'></td></tr>"
        
    return boxes

def group_boxes():
    boxes = ""

    for group in Group.objects.all().order_by('name'): 
        boxes = boxes + "<tr><td>"+group.name+"</td><td><input type='checkbox' value='"+str(group.id)+"' name='inputGroups[]'"  
        boxes = boxes +"></td></tr>"
        
    return boxes


def user_group_boxes(user):
    boxes = ""
    user_groups = user.groups.values('id')
    for group in Group.objects.all().order_by('name'): 
        boxes = boxes + "<tr><td>"+group.name+"</td><td><input type='checkbox' value='"+str(group.id)+"' name='inputGroups[]'"
        if {'id':group.id} in user_groups:
            boxes = boxes + " checked "   
        boxes = boxes +"></td></tr>"
        
    return boxes



register.simple_tag(group_boxes)
register.simple_tag(user_group_boxes)
register.simple_tag(permission_boxes)
register.simple_tag(user_permission_boxes)
register.simple_tag(group_permission_boxes)
